<template>
  <div class="map-grid-container">
    <div style="height: 100px; line-height: 100px; color: white">
      我是一个地图测试标题
    </div>
    <div ref="chartRef" class="chart-container"></div>
    <!-- 加载状态提示 -->
    <div v-if="isLoading" class="loading-mask">
      <div class="spinner"></div>
      <p>地图加载中...</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, computed } from "vue";
import * as echarts from "echarts";

// 组件核心状态
const chartRef = ref(null);
const chart = ref(null);
const isReady = ref(false);
const isLoading = ref(true); // 加载状态
const gridLines = ref([]);
const lineWidth = computed(() => 1);

const gridSize = ref(2); // 固定网格大小
const visibleRange = ref({
  minLon: 0,
  maxLon: 0,
  minLat: 0,
  maxLat: 0,
});

// 地图基础配置
const MAP_CONFIG = {
  center: [105, 35], // 中国地理中心
  zoom: 1.2, // 完整显示中国
  backgroundColor: "#8e2800",
  areaColor: "#e6f7ff",
  borderColor: "#91cc75",
  borderWidth: 1,
  beijingCoord: [116.4, 39.9],
};

// 异步加载地图数据
const loadMapData = async () => {
  try {
    const { default: chinaJson } = await import("@/assets/china.json");
    echarts.registerMap("china", chinaJson);
    return true;
  } catch (error) {
    console.error("地图数据加载失败:", error);
    return false;
  }
};

// 组件挂载初始化
onMounted(() => {
  const initTimer = setTimeout(() => {
    clearTimeout(initTimer);
    nextTick(async () => {
      if (!chartRef.value) return;
      chart.value = echarts.init(chartRef.value, null, {
        renderer: "canvas",
        useDirtyRect: true,
      });
      const dataLoaded = await loadMapData();
      if (!dataLoaded) {
        isLoading.value = false;
        return;
      }
      isReady.value = true;
      initChart();
      isLoading.value = false;
    });
  }, 100);
});

// 初始化地图图表
const initChart = () => {
  if (!isReady.value || !chart.value) return;
  const option = {
    backgroundColor: MAP_CONFIG.backgroundColor,
    tooltip: { show: false },
    geo: {
      map: "china",
      show: true,
      roam: false,
      center: MAP_CONFIG.center,
      zoom: MAP_CONFIG.zoom,
      label: { show: false },
      itemStyle: {
        areaColor: MAP_CONFIG.areaColor,
        borderColor: MAP_CONFIG.borderColor,
        borderWidth: MAP_CONFIG.borderWidth,
      },
    },
    series: [],
  };
  chart.value.setOption(option);

  // 关键修改：使用convertFromPixel替代convertToGeoCoord
  nextTick(async () => {
    await new Promise((resolve) => setTimeout(resolve, 100));

    const container = chartRef.value;
    const { width: containerWidth, height: containerHeight } =
      container.getBoundingClientRect();

    // ECharts 6.x 中使用 convertFromPixel 替代 convertToGeoCoord
    // 第一个参数指定坐标系，这里使用"geo"坐标系
    const topLeft = chart.value.convertFromPixel("geo", [0, 0]);
    const topRight = chart.value.convertFromPixel("geo", [containerWidth, 0]);
    const bottomLeft = chart.value.convertFromPixel("geo", [
      0,
      containerHeight,
    ]);
    const bottomRight = chart.value.convertFromPixel("geo", [
      containerWidth,
      containerHeight,
    ]);

    const actualMinLon = Math.min(
      topLeft[0],
      topRight[0],
      bottomLeft[0],
      bottomRight[0]
    );
    const actualMaxLon = Math.max(
      topLeft[0],
      topRight[0],
      bottomLeft[0],
      bottomRight[0]
    );
    const actualMinLat = Math.min(
      topLeft[1],
      topRight[1],
      bottomLeft[1],
      bottomRight[1]
    );
    const actualMaxLat = Math.max(
      topLeft[1],
      topRight[1],
      bottomLeft[1],
      bottomRight[1]
    );

    visibleRange.value = {
      minLon: actualMinLon,
      maxLon: actualMaxLon,
      minLat: actualMinLat,
      maxLat: actualMaxLat,
    };
    drawGrid();
  });
};

// 绘制网格
const drawGrid = () => {
  if (!isReady.value) return;
  gridLines.value = generateGridData();

  const option = chart.value.getOption();
  const nonGridSeries = option.series.filter((series) => series.type === "map");
  chart.value.setOption({
    series: [...nonGridSeries, ...gridLines.value],
  });
};

// 生成网格线数据
const generateGridData = () => {
  const lines = [];
  const { minLon, maxLon, minLat, maxLat } = visibleRange.value;

  // 计算纬线（水平线）
  const latRange = maxLat - minLat;
  const latLinesCount = Math.ceil(latRange / gridSize.value);

  for (let i = 0; i <= latLinesCount; i++) {
    const lat = Number((minLat + i * gridSize.value).toFixed(6));
    if (lat > maxLat + 0.000001) break;

    lines.push({
      type: "lines",
      name: `纬线${i}`,
      coordinateSystem: "geo",
      polyline: true,
      lineStyle: {
        width: lineWidth.value,
        color: i % 10 === 0 ? "rgba(255, 0, 0, 0.7)" : "rgba(255, 0, 0, 0.3)",
        type: i % 10 === 0 ? "solid" : "dashed",
      },
      data: [
        [
          [minLon, lat],
          [maxLon, lat],
        ],
      ],
    });
  }

  // 计算经线（垂直线）
  const lonRange = maxLon - minLon;
  const lonLinesCount = Math.ceil(lonRange / gridSize.value);

  for (let i = 0; i <= lonLinesCount; i++) {
    const lon = Number((minLon + i * gridSize.value).toFixed(6));
    if (lon > maxLon + 0.000001) break;

    lines.push({
      type: "lines",
      name: `经线${i}`,
      coordinateSystem: "geo",
      polyline: true,
      lineStyle: {
        width: lineWidth.value,
        color: i % 10 === 0 ? "rgba(0, 0, 255, 0.7)" : "rgba(0, 0, 255, 0.3)",
        type: i % 10 === 0 ? "solid" : "dashed",
      },
      data: [
        [
          [lon, minLat],
          [lon, maxLat],
        ],
      ],
    });
  }

  return lines;
};
</script>

<style scoped>
/* 保持原有样式不变 */
.map-grid-container {
  position: relative;
  width: 800px;
  height: 800px;
  margin: 20px auto;
  overflow: hidden;
  background-color: #000;
}

.chart-container {
  background-color: #ff0000;
  width: 100%;
  height: 100%;
  position: relative;
}

.map-grid-container > div:first-child {
  height: 50px;
  line-height: 50px;
  text-align: center;
  font-size: 16px;
  color: white;
}

.loading-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: rgba(255, 255, 255, 0.8);
  z-index: 10;
  gap: 16px;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #e0e0e0;
  border-top: 4px solid #42b983;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.controls,
.control-btn,
.control-btn.small-btn,
.region-selector,
.custom-region-settings,
.grid-settings,
.info {
  display: none !important;
}
</style>
